$(function() {

    function useAway(ele, fn) {
        const on = (obj, ...arg) => obj.addEventListener(...arg);

        function handle(e) {
            e = e || window.event;

            fn(ele.contains(e.target))
        }
        const eventType = ['click', 'touch'];
        for (const type of eventType) {
            on(document, type, handle, false)
        }
        return handle
    }

    const laydateBox = document.querySelector('.laydate-box');
    const selectDate = document.querySelector('.select-date');
    useAway(laydateBox, function(flag) {

        if (flag) {
            selectDate.style.display = 'block'
        } else {
            selectDate.style.display = 'none'
        }
    })



    var yearArr = [];
    var monthArr = [];
    let yearStr = '';
    let monthStr = '';
    const monthList = document.getElementById('monthList')
    const yearList = document.getElementById('yearList')
    for (var i = 1990; i < 2099; i++) {
        yearArr.push(i + "年");
        $("#").append()
        yearStr += '<option value="' + (i + "年") + '">' + i + "年" + "</option>"
    }
    for (var j = 1; j < 13; j++) {
        monthArr.push(j + "月");
        monthStr += '<option value="' + (j + "月") + '">' + j + "月" + "</option>"
    }
    yearList.innerHTML = yearStr;
    monthList.innerHTML = monthStr;
    const laydateInput = document.getElementById('laydateInput');

    function initToday() {
        var d = new Date();
        var currYear = d.getFullYear();
        var currMonth = (d.getMonth() + 1);
        var currDate = d.getDate();
        laydateInput.value = currYear + " - " + currMonth + " - " + currDate
        yearList.value = currYear + "年"
        monthList.value = currMonth + "月";
        return {
            currYear,
            currMonth,
            currDate
        }
    }
    const { currYear, currMonth, currDate } = initToday()



    const reBackBtn = document.querySelector('.reback');
    reBackBtn.addEventListener('click', e => {
        const { currYear, currMonth } = initToday()
        ergodicDate(currYear, currMonth);
        getSelectDate(currYear + " - " + currMonth + " - " + currDate)
    }, false)


    var currN = 0;
    var currK = 0;
    ergodicDate(currYear, currMonth);

    function ergodicDate(year, month) {
        var preMonth = month - 1;
        var preYear = year;
        if (preMonth < 1) {
            preMonth = 12;
            preYear - 1
        }
        var preMonthLength = getMonthLength(preYear, preMonth);
        const dayTabel = document.querySelector('.day-tabel')
        dayTabel.innerHTML = ''
        var date1 = new Date(year + "/" + month + "/" + 1).getDay();
        console.log(date1);

        function getMonthLength(year, month) {
            function isLeapYear(year) {
                return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0)
            }

            if (month == 4 || month == 6 || month == 9 || month == 11) {
                month = 30;
                return month
            }


            if (month == 2) {
                if (isLeapYear(year) == true) {
                    month = 29;
                    return month
                } else {
                    month = 28;
                    return month
                }
            } else {
                month = 31;
                return month
            }
        }

        var dayLength = getMonthLength(year, month);
        var dayArr = [];
        const FragLi = document.createDocumentFragment();
        let li1 = null,
            ul2 = null;
        for (var m = 1; m < dayLength + 1; m++) { dayArr.push(m) }
        var flag = false;
        let ul2Str = '';
        let currentIndex = 0
        for (var k = 0; k < 6; k++) {
            for (var n = 0; n < 7; n++) {
                if (k == 0 && n < date1) {
                    if (currDate < 7 && (preMonthLength - date1 + n + 1) == currDate) {
                        if (n == 6) {
                            ul2Str += `<li  data-index='${currentIndex++}' class="tabel-li preDays active weekColor">${preMonthLength - date1 + n + 1} </li>`
                        } else {
                            ul2Str += `<li  data-index='${currentIndex++}' class="tabel-li preDays active  ">${preMonthLength - date1 + n + 1} </li>`
                        }
                    } else {
                        if (n == 6) {

                            ul2Str += `<li  data-index='${currentIndex++}' class="tabel-li preDays   weekColor">${preMonthLength - date1 + n + 1} </li>`
                        } else {

                            ul2Str += `<li  data-index='${currentIndex++}' class="tabel-li preDays  ">${preMonthLength - date1 + n + 1} </li>`
                        }
                    }
                } else {
                    if (k == 0) {
                        if (currDate < 7 && (dayArr[n - date1]) == currDate) {
                            if (n == 6) {

                                ul2Str += `<li data-index='${currentIndex++}' class="tabel-li active weekColor">  ${dayArr[n - date1]}  </li>`
                            } else {
                                ul2Str += `<li data-index='${currentIndex++}' class="tabel-li active ">  ${dayArr[n - date1]}  </li>`
                            }
                        } else {
                            if (n == 6) {
                                ul2Str += `<li data-index='${currentIndex++}' class="tabel-li   weekColor">  ${dayArr[n - date1]}  </li>`

                            } else {
                                ul2Str += `<li data-index='${currentIndex++}' class="tabel-li    ">  ${dayArr[n - date1]}  </li>`
                            }
                        }
                    } else {
                        if ((k * 7 - date1 + n + 1) > dayArr.length) {
                            break
                        } else {

                            if (currDate >= 2 && (k * 7 - date1 + n + 1) == currDate) {
                                if (n == 0 || n == 6) {
                                    ul2Str += `<li data-index='${currentIndex++}'  class="tabel-li active weekColor"> ${k * 7 - date1 + n + 1}  </li>`

                                } else {
                                    ul2Str += `<li data-index='${currentIndex++}'  class="tabel-li active "> ${k * 7 - date1 + n + 1}  </li>`
                                }
                            } else {
                                if (n == 0 || n == 6) {
                                    ul2Str += `<li data-index='${currentIndex++}'  class="tabel-li   weekColor"> ${k * 7 - date1 + n + 1}  </li>`

                                } else {
                                    ul2Str += `<li data-index='${currentIndex++}'  class="tabel-li "> ${k * 7 - date1 + n + 1}  </li>`
                                }
                            }
                            if ((k * 7 - date1 + n + 1) == dayArr.length) {
                                flag = true;
                                currN = n;
                                currK = k
                            }
                        }
                    }
                }

            }

            if (flag == true) {
                for (var q = 0; q < 6 - currN; q++) {
                    ul2Str += `<li  data-index='${currentIndex++}'  class="tabel-li nextDay">${q + 1}</li>`
                }
                flag = false
            }
        }

        dayTabel.innerHTML = ul2Str
    }

    yearList.onchange = function() {
        const currMonth = monthList.value.split('月')[0]
        const currYear = yearList.value.split('年')[0]
        ergodicDate(currYear, currMonth);
        getSelectDate(currYear + " - " + currMonth + " - " + currDate)
        laydateInput.value = currYear + " - " + currMonth + " - " + currDate
    }
    monthList.addEventListener('click', function() {
        const currMonth = this.value.split('月')[0]
        const currYear = yearList.value.split('年')[0]
        ergodicDate(currYear, currMonth);
        getSelectDate(currYear + " - " + currMonth + " - " + currDate)
        laydateInput.value = currYear + " - " + currMonth + " - " + currDate
    }, false)

    let currentIndex = -1
    $(".day-tabel").on("click", ".tabel-li", function(e) {
        const target = e.target;
        if (target.tagName.toLowerCase() === 'li') {
            console.log(target);
            let date = target.innerHTML;
            let month = monthList.value.split('月')[0],
                year = yearList.value.split('年')[0],
                isChange = false;
            if (date <= 6 && target.classList.contains('nextDay')) {
                month += 1;
                isChange = true
            } else
            if (date >= 25 && target.classList.contains('preDays')) {
                month -= 1;
                isChange = true
            }

            if (month > 12) {
                year = parseInt(year) + 1
                month = 1;
                isChange = true
            }
            if (month < 1) {
                year -= 1;
                month = 12;
                isChange = true
            }

            const getDate = `${year}-${month}-${date}`;
            laydateInput.value = getDate;
            getSelectDate(getDate)
            monthList.value = month + '月';
            yearList.value = year + '年';
            const dayTabel = document.querySelector('.day-tabel')
            const li_list = dayTabel.querySelectorAll('li');

            if (currentIndex !== -1) {
                li_list[currentIndex].classList.remove('showClick')
            }
            target.classList.add('showClick');
            currentIndex = target.dataset.index

            if (isChange) {
                currentIndex = -1
                ergodicDate(year, month);
            }
        }

    })
});